package com.jacky.ocr_plugin.camera;

import android.app.Activity;
import android.content.Context;
import android.content.res.Configuration;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.ImageFormat;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.Rect;
import android.hardware.Camera;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.provider.Settings;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.Surface;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.SeekBar;
import android.widget.Toast;

import androidx.annotation.IntRange;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.jacky.util.OcrLogger;
import com.jacky.util.OcrUtil;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by lixinquan on 2018/5/25.
 */

public class OcrCameraPreviewView extends FrameLayout {

    public interface OnDoubleTapListener {
        void onDoubleTap();
    }

    public OcrCameraPreviewView(@NonNull Context context) {
        super(context);
        initView(context, null);
    }
    public OcrCameraPreviewView(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        initView(context, attrs);
    }
    public OcrCameraPreviewView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initView(context, attrs);
    }

    CameraView mInnerView;
    TouchDrawView mFocusView;
    SeekBar mSeekBar;
    View mLockScreenView;
    Point windowPoint;
    int mCurCameraFace = Camera.CameraInfo.CAMERA_FACING_BACK;
    long lastTime;
    int lastDistance;
    boolean isScreenLock;
    boolean isPrefessional;
    int mHeightPixels = 0;//=2200;
    public final static int AUTO_FOCUS_TIME_DEFAULT = 1500;
    private int autoFocusTime = AUTO_FOCUS_TIME_DEFAULT;
    private int cameraGravity = Gravity.CENTER;

    private void initView(Context context, AttributeSet attrs) {
        addView(mInnerView = new CameraView(context));
        addView(mFocusView = new TouchDrawView(context));
        windowPoint = new Point();
    }

    public void setHeightPixels(int mheightPixels) {
        this.mHeightPixels = mheightPixels;
    }

    public void setCameraGravity(int gravity){
        this.cameraGravity = gravity;
    }

    public int getCameraWidth(){
        return mInnerView == null ? 0 : mInnerView.getMeasuredWidth();
    }

    public int getCameraHeight(){
        return mInnerView == null ? 0 : mInnerView.getMeasuredHeight();
    }

    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();
        if(isPrefessional) {
            Context context = getContext();
            addView(mLockScreenView = new View(context));
            addSeekBar(context);
        }
    }

    private void addSeekBar(Context context) {
        int bright = getActivityBrightness();
        Log.d("tag", "current bright : " + bright);
        mSeekBar = new SeekBar(context);
        mSeekBar.setMax(255);
        mSeekBar.setProgress(bright);
        mSeekBar.setAlpha(0);
        mSeekBar.postDelayed(()->mSeekBar.setAlpha(1), 1000);
        mSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                changeAppBrightness(progress);
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {}

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {}
        });
        mSeekBar.setOnTouchListener(new OnTouchListener() {
            long time = 0;
            int oldProg;
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN : {
                        time = System.currentTimeMillis();
                        oldProg = mSeekBar.getProgress();
                    } break;
                    case MotionEvent.ACTION_UP :
                        if(System.currentTimeMillis() - time < 200) { //禁止点击
                            mSeekBar.setProgress(oldProg);
                            return true;
                        }
                }
                return false;
            }
        });
        int barwidth = OcrUtil.dip2px(context, 30);
        LayoutParams params = new LayoutParams(-1, barwidth);
        params.gravity = Gravity.CENTER;
        addView(mSeekBar, params);

        //将seekbar 变成竖的，并靠边显示
        int width = getResources().getDisplayMetrics().widthPixels / 2;
        mSeekBar.animate().rotation(-90).translationX(width - barwidth).setDuration(1);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        int count = event.getPointerCount();
        if(count == 1) {
            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN :
                    float x = event.getX(), y = event.getY();
                    if(mFocusView.isDoubleTap(x, y)) {
                        if(mDoubleTapListener != null) mDoubleTapListener.onDoubleTap();
                    } else {
                        mFocusView.invalidate(x, y);
                        mInnerView.focusOnTouch(x, y);
                    }
                    break;
                case MotionEvent.ACTION_UP :
                    lastTime = Long.MAX_VALUE;
                    break;
                case MotionEvent.ACTION_CANCEL :
                    lastTime = Long.MAX_VALUE;
                    break;
            }
            return true;
        } else if(isPrefessional && count >= 2) { //多个手指调焦
            switch (event.getActionMasked()) {
                case MotionEvent.ACTION_POINTER_DOWN:
                    lastDistance = distance(event);
                    lastTime = System.currentTimeMillis();
                    break;
                case MotionEvent.ACTION_MOVE:
                    long time = System.currentTimeMillis();
                    if (time - lastTime > 50) { //防止调焦过快
                        sendFocusChange(distance(event));
                        lastTime = time;
                    }
                    break;
                case MotionEvent.ACTION_POINTER_UP:
                    sendFocusChange(distance(event));
                    break;
            }
            return true;
        }
        return super.onTouchEvent(event);
    }

    private void sendFocusChange(int dis) {
        boolean up = dis > lastDistance;
        int d = Math.abs(dis - lastDistance);
        if(d > 10) { //移动的距离超过设定的值才能调焦
            lastDistance = dis;
            mInnerView.changeZoom(up);
        }
    }

    private int distance(MotionEvent event) {
        float x1 = event.getX(0);
        float x2 = event.getX(1);
        float y1 = event.getY(0);
        float y2 = event.getY(1);

        double _x = (x1- x2);
        double _y = (y1 - y2);
        return (int) Math.sqrt(_x*_x+_y*_y);
    }

    private class CameraView extends SurfaceView implements SurfaceHolder.Callback, Camera.AutoFocusCallback {

        public CameraView(Context context) {
            super(context);
            initView(context, null);
        }

        private Camera camera;//这个是hardare的Camera对象
        private int stepCount;
        private boolean isPreviewActive=true;//preview是否是活动的。防止preview是inactive时去调用对焦产生异常。

        private void initView(Context context, AttributeSet attrs) {
            SurfaceHolder holder = getHolder();
            //为了实现照片预览功能，需要将SurfaceHolder的类型设置为PUSH
            //这样，画图缓存就由Camera类来管理，画图缓存是独立于Surface的
            holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
            holder.addCallback(this);

            int widthPixels = getResources().getDisplayMetrics().widthPixels;
            //之前用dpi不管用，现在改成用像素来
            if(widthPixels >= 1080) stepCount = 4;
            else if(widthPixels >= 720) stepCount = 3;
            else if(widthPixels >= 480) stepCount = 2;
            else stepCount = 1;
            OcrLogger.d("widthPixels :" , widthPixels , ",step count:" ,stepCount);
        }

        @Override
        public void onAutoFocus(boolean success, Camera camera) {}

        @Override
        public void surfaceCreated(SurfaceHolder holder) {
            OcrLogger.w("surfaceCreated");
            switchCamera(mCurCameraFace, holder);
            mHandler.sendEmptyMessageDelayed(START_FOCUS,100);
        }

        @Override
        public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
            OcrLogger.d("surfaceChanged", width, height);
            windowPoint.set(width, height);
        }

        @Override
        public void surfaceDestroyed(SurfaceHolder holder) {
            mHandler.removeMessages(START_FOCUS);
            mHandler.removeCallbacksAndMessages(null);
            if(camera != null) {
                camera.stopPreview();
                camera.release();
            }
            camera = null;
            OcrLogger.w("surfaceDestroyed");
        }

        public void switchCamera(int cameraFace, SurfaceHolder surfaceHolder) {
            OcrLogger.w("switchCamera", cameraFace);
            if(surfaceHolder == null) {
                OcrLogger.e("surfaceHolder is null");
                return;
            }
            try {
                if(cameraFace != mCurCameraFace) {
                    camera.stopPreview();
                    camera.release();
                    camera = null;
                }
                //查询是否有设定的摄像头，没有的话就用默认的方式
                Camera.CameraInfo cameraInfo = new Camera.CameraInfo();
                int cameraCount = getNumberOfCameras();
                for(int camIdx = 0;camIdx < cameraCount;camIdx++ ){
                    Camera.getCameraInfo(camIdx,cameraInfo);
                    if(cameraInfo.facing == cameraFace){
                        camera = Camera.open(camIdx);
                        break;
                    }
                }
                if(camera == null) {
                    camera = Camera.open();
                }
                //用于获取扫描的数据
                if (camera != null && mPreviewCallback != null){
                    camera.setOneShotPreviewCallback(mPreviewCallback);
                }
            } catch (Exception e) {
                OcrLogger.e(e);
                //Snackbar.make(this, "摄像头启动失败，请检测是否有开启相机权限。" + e.getMessage(), Snackbar.LENGTH_LONG).show();
                Toast.makeText(getContext(), ("摄像头启动失败，请检测是否有开启相机权限。" + e.getMessage()), Toast.LENGTH_LONG).show();
                return;
            }

            /**
             * Camera对象中含有一个内部类Camera.Parameters.该类可以对Camera的特性进行定制
             * 在Parameters中设置完成后，需要调用Camera.setParameters()方法，相应的设置才会生效
             * 由于不同的设备，Camera的特性是不同的，所以在设置时，需要首先判断设备对应的特性，再加以设置
             * 比如在调用setEffects之前最好先调用getSupportedColorEffects。如果设备不支持颜色特性，那么该方法将
             * 返回一个null
             */
            if(getResources().getConfiguration().orientation != Configuration.ORIENTATION_LANDSCAPE) {
                //如果是竖屏
                camera.setDisplayOrientation(90);
            }
//            else{
//                camera.setDisplayOrientation(180);
//            }
            try {
                camera.setPreviewDisplay(surfaceHolder);
                //启动预览功能
                setCameraParam(cameraFace == Camera.CameraInfo.CAMERA_FACING_BACK);
                camera.startPreview();
                isPreviewActive = true;
            } catch (Exception e) {
                OcrLogger.e(e);
                // 如果出现异常，则释放Camera对象
                camera.release();
                camera = null;
            }
        }

        private boolean changeZoom(boolean up) {
            if(isPrefessional == false) return false;
            if(camera == null) return false;

            Camera.Parameters parameters = getParameters();
            if(parameters == null) return false;
            if(parameters.isZoomSupported()) {
                int i = parameters.getZoom(), j = i;
                if (up) {
                    i += stepCount;
                    int max = parameters.getMaxZoom();
                    if(i > max) {
                        i = max;
                    }
                } else {
                    i -= stepCount;
                    if(i < 0) i = 0;
                }
                Log.d("camera zoom", String.valueOf(i));
                if(j != i) {
                    parameters.setZoom(i);
                    setParameters(parameters);
                }
                return true;
            }
            return false;
        }

        private void setCameraParam(boolean isBackFacing) {
            if(camera == null) return;
            DisplayMetrics dm = getResources().getDisplayMetrics();
            float rate;
            if(getResources().getConfiguration().orientation != Configuration.ORIENTATION_LANDSCAPE) {
                 rate = 1.0f * dm.heightPixels / dm.widthPixels; //屏幕的宽高比
            }else {
                rate = 1.0f * dm.widthPixels / dm.heightPixels; //屏幕的宽高比
            }
            int height = mHeightPixels == 0 ? dm.heightPixels : mHeightPixels;
           // int height = dm.heightPixels;

            Camera.Parameters param = getParameters();
            if(param == null)return;
            if(isBackFacing) param.setFocusMode(Camera.Parameters.FOCUS_MODE_AUTO);
            param.setPictureFormat(ImageFormat.JPEG);
            Camera.Size p = getFitSize(param.getSupportedPictureSizes(), height, rate);
            if (p != null) {
                param.setPictureSize(p.width, p.height);
                OcrLogger.d("picture size:", p.width, p.height);
            }
            //屏幕预览只能选择跟手机屏幕接近的大小，才不会变形
            Camera.Size p2 = getFitSize(param.getSupportedPreviewSizes(), dm.heightPixels, rate);
            if (p2 != null) {
                param.setPreviewSize(p2.width, p2.height);
                OcrLogger.d("preview size:", p2.width, p2.height);
            }
            Camera.Size pre = p2 != null ? p2 : param.getPreviewSize();
            if(pre == null) pre = p != null ? p : param.getPictureSize();
            if(cameraGravity >= 0 && pre != null){
                FrameLayout.LayoutParams pp = (LayoutParams) getLayoutParams();
                //Preview预览的宽高需要倒置
                float r = pre.width*1f / pre.height;
                int h = (int) (OcrCameraPreviewView.this.getMeasuredWidth() * r);
                pp.height = Math.min(h, pp.height);
                pp.gravity = cameraGravity;
                setLayoutParams(pp);
                OcrLogger.d(OcrCameraPreviewView.this.getMeasuredWidth(),"params height", pp.height,h,"preview w*h",pre.width, pre.height,r);
            }
            setParameters(param);
            if (param.isZoomSupported()) {
                OcrLogger.d("max zoom", param.getMaxZoom());
            }
        }

        /**
         *  获取相机最适合使用的分辨率
         */
        private Camera.Size getFitSize(List<Camera.Size> sizeList, int h, float rate) {
            //size的width和height是横屏状态的高宽，竖屏下需要对换下
            int width = h;

            int offset = Integer.MAX_VALUE;
            Camera.Size ss = null;
            for(Camera.Size size : sizeList) {
                if(size.width >= width && equalRate(size, rate)) {
                    if((size.width - width) < offset) {
                        offset = size.width - width;
                        ss = size;
                    }
                }
            }
            return ss;
        }

        private boolean equalRate(Camera.Size s, float rate) {
            float r = (float) (s.width) / (float) (s.height);
            if (Math.abs(r - rate) <= 0.2) {
                return true;
            } else {
                return false;
            }
        }

        public void focusOnTouch(float x, float y) {
            if(isPreviewActive == false || camera == null) {
                OcrLogger.d("focusOnTouch return, isPreviewActive",isPreviewActive);
                return;
            }
            Rect focusRect = calculateTapArea(windowPoint,x, y, 1f);
            Rect meteringRect = calculateTapArea(windowPoint,x , y, 1.5f);

            Camera.Parameters parameters = getParameters();
            if(parameters == null)return;
            if (parameters.getMaxNumFocusAreas() > 0) {
                List<Camera.Area> focusAreas = new ArrayList<Camera.Area>();
                focusAreas.add(new Camera.Area(focusRect, 1000));
                parameters.setFocusAreas(focusAreas);
            }
            if (parameters.getMaxNumMeteringAreas() > 0) {
                List<Camera.Area> meteringAreas = new ArrayList<Camera.Area>();
                meteringAreas.add(new Camera.Area(meteringRect, 1000));
                parameters.setMeteringAreas(meteringAreas);
            }
            setParameters(parameters);
            autoFocus(this);
        }
        private Rect calculateTapArea(Point point, float rawX, float rawY, float coefficient) {
            float focusAreaSize = 300;
            int areaSize = Float.valueOf(focusAreaSize * coefficient).intValue();
            int centerX = (int) (rawX / point.x * 2000 - 1000);
            int centerY = (int) (rawY / point.y * 2000 - 1000);

            int left = clamp(centerX - areaSize / 2, -1000, 1000);
            int right = clamp(left + areaSize, -1000, 1000);
            int top = clamp(centerY - areaSize / 2, -1000, 1000);
            int bottom = clamp(top + areaSize, -1000, 1000);

            return new Rect(left, top, right, bottom);
        }
        private int clamp(int x, int min, int max) {
            return x >= max ? max : (x < min ? min : x);
        }

        public void takePicture(Camera.PictureCallback callback) {
            if(camera == null || isPreviewActive == false) {
                OcrLogger.e("takePicture isPreviewActive takePicture return",isPreviewActive);
                return;
            }
            isPreviewActive = false;
            camera.takePicture(null, null, callback);
        }

        public void startPreview() {
            if(camera == null) return;
            camera.stopPreview();
            camera.startPreview();
            isPreviewActive = true;
        }

        public void stopPreview() {
            if(camera == null) return;
            camera.stopPreview();
            isPreviewActive = false;
        }

        public Camera.Parameters getParameters(){
            if(camera == null) return null;
            try {
                return camera.getParameters();
            }catch (Exception e){
                e.printStackTrace();
            }
            return null;
        }

        public void setParameters(Camera.Parameters parameters){
            if(camera == null)return;
            try {
                camera.setParameters(parameters);
            }catch (Exception e){
                e.printStackTrace();
            }
        }

        public void release(){
            if(camera != null) {
                camera.stopPreview();
                camera.release();
            }
            camera = null;
        }
    }

    private OnDoubleTapListener mDoubleTapListener;
    public void setDoubleClick(OnDoubleTapListener listener) {
        mDoubleTapListener = listener;
    }

    private Camera.PreviewCallback mPreviewCallback;
    public void setPreviewCallback(Camera.PreviewCallback previewCallback) {
        this.mPreviewCallback = previewCallback;
        if (mInnerView != null && mInnerView.camera != null){
            mInnerView.camera.setOneShotPreviewCallback(mPreviewCallback);
        }
    }

    /**
     * 设置自动聚焦时间
     * @param milli 单位毫秒
     */
    public void setAutoFocusTime(int milli){
        autoFocusTime = milli;
    }

    private class TouchDrawView extends View {
        int X; // X坐标
        int Y; // Y坐标
        int radius; // 半径
        Paint paint; // 画笔

        public TouchDrawView(Context context) {
            super(context);
            paint = initPaint();
        }

        @Override
        protected void onDraw(Canvas canvas) {
            if(radius == 0) return;
           canvas.drawCircle(X, Y, radius, paint);
            if(radius == 100) {
                radius = 85;
                postInvalidateDelayed(150);
            } else if(radius == 85) {
                radius = 70;
                postInvalidateDelayed(150);
            } else if(radius == 70) {
                radius = 0;
                postInvalidateDelayed(800);
            }
        }
        public void invalidate(float x, float y) {
            radius = 100;
            this.X = (int) x;
            this.Y = (int) y;
            invalidate(X - 120, Y - 120, X + 120, Y + 120);
        }
        private Paint initPaint() {
            Paint paint = new Paint();
            paint.setAntiAlias(true);// 抗锯齿
            paint.setStrokeWidth(6);// 描边宽度
            paint.setStyle(Paint.Style.STROKE);// 圆环
            paint.setAlpha(255 - 80);// 透明度
            paint.setColor(Color.WHITE);// 颜色
            return paint;
        }
        public boolean isDoubleTap(float x, float y) {
            if(radius < 70) return false;
            return (Math.abs(x - X) < radius && Math.abs(y - Y) < radius);
        }
    }

    public int getNumberOfCameras() {
        return Camera.getNumberOfCameras();
    }

    /**
     * 确认摄像头开启状态，没开启则重新开启
     */
    public void checkCameraOpen(){
        if(mInnerView.camera == null){
            mInnerView.switchCamera(mCurCameraFace,mInnerView.getHolder());
        }
    }
    /**
     * 切换前后摄像头
     */
    public void switchCamera() {
        int i;
        if(mCurCameraFace == Camera.CameraInfo.CAMERA_FACING_BACK) {
            i = Camera.CameraInfo.CAMERA_FACING_FRONT;
        } else {
            i = Camera.CameraInfo.CAMERA_FACING_BACK;
        }
        mInnerView.switchCamera(i, mInnerView.getHolder());
        mCurCameraFace = i;
    }

    public void takePicture(Camera.PictureCallback callback) {
        mInnerView.takePicture(callback);
    }

    public void startPreview() {
        mInnerView.startPreview();
    }

    public void stopPreview() {
        mInnerView.stopPreview();
    }

    public void releaseCamera() {
        mInnerView.release();
    }

    public boolean openFlashlight(){
        if(isCameraFacingBack() && mInnerView.camera != null){
            return setFlash(Camera.Parameters.FLASH_MODE_TORCH);
        }
        return false;
    }

    public boolean closeFlashlight(){
        if(isCameraFacingBack() && mInnerView.camera != null){
            return setFlash(Camera.Parameters.FLASH_MODE_OFF);
        }
        return false;
    }

    private boolean setFlash(String mode){
        if(mInnerView.camera == null)return false;
        Camera.Parameters parameters = this.mInnerView.camera.getParameters();
        if (parameters.getSupportedFlashModes() == null) {
            return false;
        }
        //模式相同，不用处理
        if (parameters.getFlashMode().equals(mode)) {
            return false;
        }
        parameters.setFlashMode(mode);
        mInnerView.setParameters(parameters);
        return mInnerView.camera.getParameters().getFlashMode().equals(mode);
    }

    public boolean isScreenLock() {
        return isScreenLock;
    }

    public void toggleLock() {
        isScreenLock = !isScreenLock;
        if (getContext() == null)return;
        if(isScreenLock) {
            Toast.makeText(getContext(), "您开启了锁屏功能", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(getContext(), "您关闭了锁屏功能", Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 改变App当前Window亮度
     *
     * @param brightness
     */
    private void changeAppBrightness(@IntRange(from = 0, to = 255)int brightness) {
        if(isScreenLock) return;

        Activity activity = (Activity) getContext();
        Window window = activity.getWindow();
        WindowManager.LayoutParams lp = window.getAttributes();
        if (brightness == -1) {
            lp.screenBrightness = WindowManager.LayoutParams.BRIGHTNESS_OVERRIDE_NONE;
        } else {
            lp.screenBrightness = (brightness <= 0 ? 1 : brightness) / 255f;
        }
        window.setAttributes(lp);
        mLockScreenView.setBackgroundColor(Color.argb(255 - brightness, 0, 0,0));
    }

    private int getActivityBrightness() {
        int screenBrightness = -1;
        try {
            screenBrightness = Settings.System.getInt(getContext().getContentResolver(),
                    Settings.System.SCREEN_BRIGHTNESS);
        } catch (Settings.SettingNotFoundException e) {
            e.printStackTrace();
        }
        return screenBrightness;
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if(isScreenLock) return true;
        return super.dispatchTouchEvent(ev);
    }

    public void autoFocus(Camera.AutoFocusCallback callback) {
        if(mInnerView.isPreviewActive && mInnerView.camera != null) {
            try {
                mInnerView.camera.autoFocus(callback);
                //每次聚焦则设置一帧预览数据，该方法OneShot为一次性
                if (mPreviewCallback != null){
                    mInnerView.camera.setOneShotPreviewCallback(mPreviewCallback);
                }
            }catch (Exception e) {
                OcrLogger.w(e);
            }
        }
    }

    public boolean isCameraFacingBack() {
        return mCurCameraFace == Camera.CameraInfo.CAMERA_FACING_BACK;
    }

    private static final int START_FOCUS = 2;
    private final Handler mHandler = new Handler(Looper.getMainLooper()){
        @Override
        public void handleMessage(Message msg) {
            handleInnerMessage(msg.what);
        }
    };

    private void handleInnerMessage(int msg) {
        switch (msg){
            case START_FOCUS:
                if (mInnerView != null && mInnerView.camera != null){
                    autoFocus(mInnerView);
                }
                //1.5秒后再次聚焦 聚焦
                mHandler.sendEmptyMessageDelayed(START_FOCUS,autoFocusTime);//1500
                break;
        }
    }

    public Camera.Parameters getCameraParameter(){
        if (mInnerView != null && mInnerView.camera != null){
            return mInnerView.getParameters();
        }
        return null;
    }

    public int getPreviewWidth() {
        Camera.Parameters parameters = getCameraParameter();
        return parameters != null ? parameters.getPreviewSize().width : 0;
    }

    public int getPreviewHeight() {
        Camera.Parameters parameters = getCameraParameter();
        return parameters != null ? parameters.getPreviewSize().height : 0;
    }
    ///显示方向
    public int getDisplayOrientation(){
        WindowManager windowManager = (WindowManager)this.getContext().getSystemService(Context.WINDOW_SERVICE);
        int or = windowManager.getDefaultDisplay().getRotation();
        switch (or){
            case Surface.ROTATION_90 : return 90;
            case Surface.ROTATION_180 : return 180;
            case Surface.ROTATION_270 : return 270;
            case Surface.ROTATION_0 :
            default:
                return 0;
        }
    }
    ///获取camera画面需要旋转的角度
    ///因为Camera.open()默认后置摄像头
    public int getCameraAngle(){
        //来自 Camera.setDisplayOrientation
        int degrees = getDisplayOrientation();
        int orientation = getCameraOrientation(mCurCameraFace);
        int result;
        if (mCurCameraFace == Camera.CameraInfo.CAMERA_FACING_FRONT) {
            result = (orientation + degrees) % 360;
            result = (360 - result) % 360;  // compensate the mirror
        } else {  // back-facing
            result = (orientation - degrees + 360) % 360;
        }
//        OcrLogger.d("tag","flutter to android, getDisplayOrientation " + degrees + " orientation "
//                + orientation+ " result " + result);
        return result;
//        int cameraO = getCameraOrientation(Camera.CameraInfo.CAMERA_FACING_BACK);
//        int displayO = getDisplayOrientation();
//        OcrLogger.d("tag","flutter to android, cameraOrientation " + cameraO + " displayOrientation " + displayO);
//        return (getCameraOrientation(mCameraFace) - getDisplayOrientation() + 360) % 360;
    }

    ///获取手机相机方向 https://zhuanlan.zhihu.com/p/110944780
    public int getCameraOrientation(int cameraId){
        Camera.CameraInfo info =new Camera.CameraInfo();
        Camera.getCameraInfo(cameraId,info);
        return info.orientation;
    }
}
